var itemno = "";
var applyid = "";
var nodeno = "";
var orgcode = "";
var nextnodecode1 = "";
var selectID = "userlist";
var applyno = "";
var nowindex=1;

$(function(){
	applyno = getUrlParam("applyno");
	itemno = getUrlParam("itemno");
	bindOrg2('org');
//	bindDict("provincecode","DM_SF",null,null,false);
//	bindDict("citycode","DM_CS",null,null,false);
	initFileInput('upload', null, null);
//	上传文本控件关闭事件 -- 清除内容
	$('#fileuploadmodal').on('hide.bs.modal', function () {
        setTimeout(function(){
        	$('.fileinput-remove').trigger('click');
        }, 1000);
	})
	
	$('#submit').click(function(){
		save(true);
	})	
	$('#save').click(function(){
		save(false);
	})
	
	bindApply(applyno);
	
	
	
})


function bindApply(applyno){
	$.ajax({ 
		url: basePath() + 'business/getapplyinfo.do',
		data: {"applyno": applyno},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
	    		var jsonApply = data.datas.apply;
	    		var jsonBusiness = data.datas.business;
//	    		var jsonMaterial = data.datas.material;
//	    		var jsonShip = data.datas.ship;
//	    		var jsonCoordinate = data.datas.coordinate;


	    		applyid = jsonApply.applyid;
	    		
	    		bindApplyForm(jsonApply);
	    		
	    		//绑定业务资料
	    		bindBusinessForm(jsonBusiness);

	    		//绑定证书
	    		bindCertificate(jsonBusiness["recordcertificatelist"]);
	    	}
      	}
	});
}

function bindApplyForm(jsonApply){
	
	for(var d in jsonApply){//遍历json对象的每个key/value对,p为key
		
		$('#' + d).html(jsonApply[d] == '' ? '/' : jsonApply[d]);
		$('#' + d).attr("value",jsonApply[d] == '' ? '' : jsonApply[d]);
	}
	$("#org").attr("value",jsonApply["orgname"]);
}

function bindBusinessForm(jsonBusiness){

	for ( var d in jsonBusiness) {// 遍历json对象的每个key/value对,p为key
		if (d == 'applydate') {
			$('[name="' + d + '"]').html(formatDate(jsonBusiness[d], 'yyyy-mm-dd'));
		} else {
			$('[name="' + d + '"]').val(jsonBusiness[d] == '' ? '' : jsonBusiness[d]);
		}
	}
	
//	if (jsonBusiness['oldapplyno'] != '' && undefined != jsonBusiness['oldapplyno']) {
//		$('.change').show();
//		$('#itemname').html($('#itemname').html() + '（变更）');
//	}
}



function save(issubmit){
	
	var param = {};
	var applyData = $('#Apply').serializeObject();
	var businessData = $('#Business').serializeObject();
	var recordcertificate=$("#recordcertificate").serializeObjectArray();
	var recordcertificateDate = [];
	for(var iRecordcertificate = 0; iRecordcertificate < recordcertificate.length; iRecordcertificate++){
		if(undefined != recordcertificate[iRecordcertificate]["fileid"]){
			recordcertificateDate.push(recordcertificate[iRecordcertificate]);
		}
	}
	
	param['itemno']  = getUrlParam('itemno');
	param['issubmit'] = issubmit;
	param['Apply'] = applyData;
	param['Business'] = businessData;
	param['Business']['recordcertificate']=recordcertificateDate;

	if(!checkData(param)){
		return;
	}
	
	if(getUrlParam('change') == '1')
		delete applyData['applyid'];
	
	$.ajax({ 
		method: 'post',
		url: projectPath + 'business/apply.do',
		data: JSON.stringify(param),
        dataType: 'json',  
        contentType:'application/json;charset=UTF-8', 
		success: function(data){
			var msa = data.info;

			var applyno = "";
			if(data.result == 1){
				if(issubmit)
					msa = "提交成功！";
				else
					msa = "保存成功！";
				
				applyno = data.datas.applyno;
				msa += '<br/><span style="color:red;">申请单号是：' + applyno + '</span>'; 
			}
			
			$.confirm({
			    title: '提示!',
			    content: msa,
			    confirmButton: '确定',
			    cancelButton: '取消',
			    confirm: function(){
			    	if(msa.indexOf("未登录") < 0){
			    		var itemno = $('[name="itemno"]').val();
			    		window.location.href = "detail.html?applyno=" + applyno + "&itemno=" + itemno;
			    	}
			    }
			});
		}
	});
}

function checkData(param){
	var check = true;
	var checkErrorStr = '';
	
	var checkApplyStr = ['orgcode'];
	for(var i = 0; i < checkApplyStr.length; i++){
		if($('[name="'+checkApplyStr[i]+'"]').val() == ''){
			checkErrorStr += $('[name="'+checkApplyStr[i]+'"]').attr('placeholder') + '<br />';
		}
	}
	
	var checkBusinessStr = ['companyname','companycode','email','corporation','companynameen','contactperson','contactphone','provincecode','citycode','street', 'businessaddress'];	
	
	for(var i = 0; i < checkBusinessStr.length; i++){
		if($('[name="'+checkBusinessStr[i]+'"]').val() == ''){
			checkErrorStr += $('[name="'+checkBusinessStr[i]+'"]').attr('placeholder') + '<br />';
		}
	}
	
	if(checkErrorStr != ''){
		$.alert({
		    title: '提示!',
		    content: checkErrorStr,
		    confirmButton: '确定'
		});
		
		check = false;
	}
	
	return check;
}

function addrecordcertificate(){
	var html = ''+
	  '	<tr>'+
	  '		<td>'+
	  '			<select class="form-control" name="certificatetype" id="certificatetype'+nowindex+'">'+
	  '		<input type="hidden"  class="form-control" name="recordtype"  value="2"></td>'+
	  '		<td>'+
	  '			<input type="date" class="form-control" name="issuedate" id="issuedate'+nowindex+'">'+
	  '		</td>'+
	  '		<td>'+
	  '			<input type="date" class="form-control" name="effectivedate" id="effectivedate'+nowindex+'">'+
	  '		</td>'+
//	  '		<td>'+
//	  '			是<input type="checkbox" onclick="permanentchange(this)" name="permanent"  value="1" id="permanenty'+nowindex+'">否<input type="checkbox" onclick="permanentchange(this)" name="permanent" checked value="0" id="permanentn'+nowindex+'">'+
//	  '		</td>'+
	  '		<td id="filename'+ nowindex +'"></td>'+
	  '	    <td><button type="button"  onclick="openModal('+nowindex+')" class="btn btn-success" ><span class="glyphicon glyphicon-upload"></span>上传</button>'+
	  '			<input type="hidden" id="upload'+nowindex+'" class="form-control" name="fileid"  value=""></td>'+
	  '		<td>'+
	  '			<button type="button"  onclick="deleterecordcertificate(this)" class="btn btn-danger btn-sm" style="margin-right:10px;"><span class="glyphicon glyphicon-minus"></span></button>'+
	  '		</td>'+
	  '	</tr>';	
	
	$("#recordcertificate").find('tbody').append(html);
	bindDict("certificatetype"+nowindex,"DM_DWBAZSLX",null);
	nowindex++;
}
function deleterecordcertificate(button){
	$(button).parent().parent().remove();
}


function initFileInput(ctrlcss, params, data) {
	
	var urls = [];
	if(data != null){
		for(var i = 0; i < data.length; i++){
			urls[i] = data[i].url;
		}
	}
    var control = $('.' + ctrlcss);
    control.fileinput({
        theme: 'explorer-fa',
        language: 'zh', //设置语言
        uploadUrl: projectPath + "share/upload_fileinput.do", //上传的地址
		allowedFileExtensions : ['jpg', 'png','gif','txt','sql','xlsx','xls','pdf','pptx','docx','doc','jpeg'],//接收的文件后缀
        uploadAsync: true, //默认异步上传
        showUpload: true, //是否显示上传按钮
        showRemove : true, //显示移除按钮
        showPreview : true, //是否显示预览
        showCaption: false,//是否显示标题
        browseClass: "btn btn-primary", //按钮样式
        enctype: 'multipart/form-data',
        validateInitialCount:true,
        overwriteInitial: false,
        initialPreviewAsData: true,
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
        initialPreview: urls,
	    initialPreviewConfig: data,

    }).on('filepreupload', function(event, data, previewId, index) {     //上传中
        var form = data.form, files = data.files, extra = data.extra,
        response = data.response, reader = data.reader;
        console.log(JSON.stringify(data.form));
        console.log('文件正在上传');
    }).on("fileuploaded", function (event, data, previewId, index) {    //一个文件上传成功
    	 console.log('文件上传成功！');
         
         var resultData = data.response;
         var fileid = resultData.datas[0].fileid;
         var filename = '<p id="'+ fileid +'"><a href="/gahCSP/share/downFiles.do?filename='+ resultData.datas[0].filename +'&fileid='+ fileid +'">' + resultData.datas[0].filename + '</a><span class="glyphicon glyphicon-remove" style="color:red;cursor:pointer;" onclick="deleteFile(\''+ fileindex +'\', \''+ fileid +'\')"></span></p>';
         var fileids = $('#upload' + fileindex).attr("value");
         var filenames = $('#filename' + fileindex).html();
         if(fileids == ''){
         	fileids = fileid;
         	filenames = filename;
         }
         else{
         	fileids += ',' + fileid;
         	filenames += filename;
         }

         $('#upload' + fileindex).attr("value", fileids);
         
         $('#filename' + fileindex).html(filenames);

     	 $('#fileuploadmodal').modal('hide');
     	
    }).on('fileerror', function(event, data, msg) {  //一个文件上传失败
        console.log('文件上传失败！'+data.id);
    }).on('filepredelete', function(event, key, jqXHR, data) {  
        alert(key);   
        return;
    });  
}

function openModal(index){
	fileindex=index;
	$('#fileuploadmodal').modal('show');
}

function changeCity(provincecode){
	$('#citycode').empty(); 
	bindDict("citycode","DM_CS",null,provincecode);
}

function deleteFile(index, fileid){
	var fileidsNew = "";
	var fileids = $('#upload' + index).attr('value');
	for(var i=0; i<fileids.split(',').length; i++){
		if(fileids.split(',')[i] != fileid){
			fileidsNew += fileids.split(',')[i] + ',';
		}
	}
	if(fileids.split(',').length > 0)
		fileidsNew = fileidsNew.substring(0, fileidsNew.length - 1);
	
	$('#' + fileid).remove();

	$('#upload' + index).attr('value', fileidsNew);
}

function bindOrg(obj){

	$.ajax({ 
		method: 'post',
		url: projectPath + "share/getOrg.do",
		dataType: "json",
		async:false,
		contentType: "application/json",
		success: function(data){
		    var cityPicker = new IIInsomniaCityPicker({
		        data: data,
		        target: '#' + obj,
		        callback: function(id){
		        	var id = $('#' + obj).attr("data");
		        	var name = $('#' + obj).val();
		        	
		        	$('#orgcode').val(id);
		        	$('#orgname').val(name);
		        }
		    });
		    cityPicker.init();
		}
	});
}

function bindOrg2(obj){
	$.ajax({ 
		method: 'post',
		url: projectPath + "share/getOrg.do",
		dataType: "json",
		contentType: "application/json",
		success: function(data){
			//常用海事机构
			var historyjson = data.hisResult;
			//海事机构
			var orgAlljson = data.result;
			
			var topCode = '000000';
			var orgList = JSON2ARRAY3(orgAlljson, topCode);
			var orgHistoryList = JSON2ARRAY2(historyjson);
			InitList(obj, topCode, orgList, orgHistoryList);
		}
	});
}

function bindCertificate(recordcertificatelist){
	for(var i=0;i<recordcertificatelist.length;i++){
//		var html = ''+
//		  '	<tr>'+
//		  '		<td>'+
//		  			recordcertificatelist[i]["certificatetype"]+
//		  '		<input type="hidden" name="certificatetype" id="certificatetype'+nowindex+'" value="'+recordcertificatelist[i]["certificatetype"]+'">'+
//		  '		<input type="hidden"  class="form-control" name="recordtype"  value="2"></td>'+
//		  '		<td>'+
//		  '			<input type="date" class="form-control" name="issuedate" id="issuedate'+nowindex+'">'+
//		  '		</td>'+
//		  '		<td>'+
//		  '			<input type="date" class="form-control" name="effectivedate" id="effectivedate'+nowindex+'">'+
//		  '		</td>'+
////		  '		<td>'+
////		  '			是<input type="checkbox" onclick="permanentchange(this)" name="permanent"  value="1" id="permanenty'+nowindex+'">否<input type="checkbox" onclick="permanentchange(this)" name="permanent" checked value="0" id="permanentn'+nowindex+'">'+
////		  '		</td>'+
//		  '		<td id="filename'+ nowindex +'"></td>'+
//		  '	    <td><button type="button"  onclick="openModal('+nowindex+')" class="btn btn-success" ><span class="glyphicon glyphicon-upload"></span>上传</button>'+
//		  '			<input type="hidden" id="upload'+nowindex+'" class="form-control" name="fileid"  value=""></td>'+
//		  '		<td>'+
//		  '			<button type="button"  onclick="deleterecordcertificate(this)" class="btn btn-danger btn-sm" style="margin-right:10px;"><span class="glyphicon glyphicon-minus"></span></button>'+
//		  '		</td>'+
//		  '	</tr>';	
//
//		$("#recordcertificate").find('tbody').append(html);

		$("#issuedate"+nowindex).val( formatDate(recordcertificatelist[i]["issuedate"], 'yyyy-mm-dd'));
		$("#effectivedate"+nowindex).val( formatDate(recordcertificatelist[i]["effectivedate"], 'yyyy-mm-dd'));
		
		for(var j=0;j<recordcertificatelist[i]["recordcertificatefile"].length;j++){
	        var filename = '<p id="'+ recordcertificatelist[i]["recordcertificatefile"][j]["FILEID"] +'"><a href="/gahCSP/share/downFiles.do?filename='+ recordcertificatelist[i]["recordcertificatefile"][j]["FILENAME"] +'&fileid='+ recordcertificatelist[i]["recordcertificatefile"][j]["FILEID"] +'">' + recordcertificatelist[i]["recordcertificatefile"][j]["FILENAME"] + '</a><span class="glyphicon glyphicon-remove" style="color:red;cursor:pointer;" onclick="deleteFile(\''+ nowindex +'\', \''+ recordcertificatelist[i]["recordcertificatefile"][j]["FILEID"] +'\')"></span></p>';
	        var fileids=$('#upload' + nowindex).val();
	        if(fileids==""){
	        	fileids+=recordcertificatelist[i]["recordcertificatefile"][j]["FILEID"];
	        }else{
	         	fileids += ',' + recordcertificatelist[i]["recordcertificatefile"][j]["FILEID"];
	         }
			$("#filename"+nowindex).append(filename);
	        $('#upload' + nowindex).attr("value", fileids);

		}
		
		
		nowindex++;
		
		
		
		
		
		
		
//		var html='	<tr>'+
//		  '		<td>'+
//		  recordcertificatelist[i]["certificatetypename"]+
//		  '		</td>'+
//		  '		<td>'+
//		  formatDate(recordcertificatelist[i]["issuedate"])	+
//		  '		</td>'+
//		  '		<td>'+
//		  formatDate(recordcertificatelist[i]["effectivedate"])	+
//		  '		</td>'+
//		  '		<td id="filename'+ recordcertificatelist[i]["certificateid"]+'"></td>'+
//		  '	</tr>';	
//		$("#recordcertificate").find('tbody').append(html);
//		
//		
	}
}